@POST.update-wiki copy.php

<?php


function verifyGithubWebhook($sshDir, $keyFileName,$writeLog=false,$printLog=false){
    $body = trim(file_get_contents("php://input"));
    $headers = getallheaders();
    
    $log = $sshDir.'/log';
    $repo = $_POST['repository']['full_name'];
    $keyFileName = 'github_taeluf_webhook';


    $gitKeySHA1Hashed = $headers['X-Hub-Signature'];
    $localKeyRaw = trim(shell_exec('ssh-keygen -y -f '.$sshDir.'/'.$keyFileName));
    $localKeySHA1Hashed = 'sha1='.hash_hmac('sha1',$body,$localKeyRaw);

    $success = hash_equals($localKeySHA1Hashed,$gitKeySHA1Hashed);

    if ($writeLog||$printLog){
        $logData = "Repo '{$repo}'\n"."Received:\n{$gitKeySHA1Hashed}\n\nLocallyHashed:\n{$localKeySHA1Hashed}\n\n";
        $logData .= $success ? 'SUCCESS' : 'FAILURE';
        $logData .= "\n\n----------------------------------\n\n";
    }
    if ($writeLog)file_put_contents($log,$logData,FILE_APPEND|LOCK_EX);
    if ($printLog)echo $logData;

    return $success;    
}

function isValidGitRepo($repoName){

    $validRepos = [
        'RDB',
        'PHP-Documentor',
        'Liaison',
        'Better-Regex',
        'Wikitten-Liaison',
    ];

    if (in_array($repoName,$validRepos))return true;

    return false;
}


function updateGitRepo($dir,$repoName){

    $repoInfo = $_POST['repository'];
    $defaultBranch = $repoInfo['default_branch'];
    $cleansedBranch = preg_replace('/[^a-zA-Z\_\-0-9]/','',$defaultBranch);
    if ($cleansedBranch!=$defaultBranch){
        echo "Receive default branch: ".$defaultBranch; 
        echo "\ncleansed: ".$defaultBranch."\n";
        echo "Cannot checkout default branch.\n";
        $defaultBranch = '';
    }

    $proj = $repoName;
    if (!isValidGitRepo($repoName)){
        echo "Repo name '{$repoName}' is invalid.";
        return;
    }
    if (!is_dir($dir)){
        echo "project root dir '{$dir}' does not exist. Cannot update git repo.";
        return;
    }
    echo "\nWill try checkout default branch: '{$defaultBranch}'\n";
    $url = "https://github.com/Taeluf/".$proj.'.git';
    $projectDir = $dir.$proj.'/';
    $srcDir = $projectDir.'0-src/';
    $dirCheck = $srcDir.'.git';
    if (is_dir($dirCheck)){
        $command = "cd {$srcDir};\ngit pull;\n git checkout {$defaultBranch};\n";
        // $command .= "cd ..;\n y | mv -i 0-src/0-docs/* ./;\n";
        // $output = shell_exec($command);
        $command .="cd ..";
        $moveProjToSource = "mv 0-src ../temp-{$proj};cd ..; rm -rf {$proj}; mkdir {$proj}; mkdir {$proj}/0-src; mv temp-{$proj}/* {$proj}/0-src/;mv temp-{$proj}/.[!.]* {$proj}/0-src/; rm -rf temp-{$proj};";
        $command .= $moveProjToSource;
        $output = shell_exec($command);

        $files = scandir($srcDir);
        $docsDir = null;
        foreach ($files as $f){
            if ($f=='0-docs'){
                $docsDir = $f;
                break;
            }
            if (strpos($f,'doc')!==false){
                $docsDir = $f;
                break;
            }
        }
        if ($docsDir==null){
            echo "Docs dir is null. Cannot move";
        } else {
            $moveDocsToSource = "cd {$dir}; cp -R {$proj}/0-src/{$docsDir}/* {$proj}/";
            shell_exec($moveDocsToSource);
        }

        // echo $output;
        echo "Did git pull on '{$proj}'\n<br>\n";
        return;
    } 
    if (is_dir($srcDir)&&count(scandir($srcDir))>2){
        echo "We can't git clone or git pull '{$proj}' because the directory exists, has content, but does NOT have a .git directory.\n<br>\n";
        return;
    }
    $command = "cd {$dir};\ngit clone https://github.com/Taeluf/{$proj}.git;\n git checkout {$defaultBranch};\n";
    $moveProjToSource = "mv {$proj} temp-{$proj}; mkdir {$proj}; mkdir {$proj}/0-src; mv temp-{$proj}/* {$proj}/0-src/;mv temp-{$proj}/.[!.]* {$proj}/0-src/; rm -rf temp-{$proj};";
    $command .= $moveProjToSource;
    $output = shell_exec($command);

    $files = scandir($srcDir);
    $docsDir = null;
    foreach ($files as $f){
        if ($f=='0-docs'){
            $docsDir = $f;
            break;
        }
        if (strpos($f,'doc')!==false){
            $docsDir = $f;
            break;
        }
    }
    if ($docsDir==null){
        echo "Docs dir is null. Cannot move";
    } else {
        $moveDocsToSource = "cd {$dir}; cp -R {$proj}/0-src/{$docsDir}/* {$proj}/";
        shell_exec($moveDocsToSource);
    }

    echo "Did git clone on '{$proj}'\n<br>\n";
    // echo $output;

}





$payload = $_POST['payload'];
$json = json_decode($payload,true);





$_POST = $json;
$repoName = $_POST['repository']["name"];
$wikiDir = dirname(dirname(dirname(__DIR__))).'/6-Wiki/';

$sshDir = '~/.ssh/';
$keyFileName = 'github_taeluf_webhook';

echo "Start Verification\n";
echo "Working on repo '{$repoName}'";
if (verifyGithubWebhook($sshDir,$keyFileName)){
    echo "Github webhook verified successfully.\n";
    updateGitRepo($wikiDir, $repoName);
    if ($repoName==''){
        print_r($_POST);
    }
} else {
    echo "The github webhook failed to verify.";
}




print_r($_POST['repository']);


exit;